package org.apache.ibatis.executor;

import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.List;

/**
 * @author Clinton Begin
 */
public class SimpleExecutor extends BaseExecutor {

    public SimpleExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    @Override
    public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
        Statement stmt = null;
        try {
            Configuration configuration = ms.getConfiguration();
            // 创建 StatementHandler
            StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
            // 创建 Statement
            stmt = prepareStatement(handler, ms.getStatementLog());
            // 调用 StatementHandler 的 update 方法
            return handler.update(stmt);
        } finally {
            closeStatement(stmt);
        }
    }

    @Override
    public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        Statement stmt = null;
        try {
            Configuration configuration = ms.getConfiguration();
            // 1.创建 StatementHandler
            // 创建StatementHandler对象，实际返回的是RoutingStatementHandler对象，
            // 其中根据MappedStatement.statementType选择具体的StatementHandler实现
            StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
            // 2.创建 Statement
            // 完成Statement的创建和初始化，该方法首先会调用StatementHandler.prepare()方法创建Statement对象，
            // 然后调用StatementHandler.parameterize()方法处理占位符
            stmt = prepareStatement(handler, ms.getStatementLog());
            // 3.执行查询操作
            // 调用StatementHandler.query()方法，执行SQL语句，并通过ResultSetHandler完成结果集的映射
            return handler.<E>query(stmt, resultHandler);
        } finally {
            // 4.关闭Statement对象
            closeStatement(stmt);
        }
    }

    @Override
    protected <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException {
        Configuration configuration = ms.getConfiguration();
        StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, null, boundSql);
        Statement stmt = prepareStatement(handler, ms.getStatementLog());
        return handler.<E>queryCursor(stmt);
    }

    @Override
    public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {
        return Collections.emptyList();
    }

    /**
     * 1.获取数据库连接
     * 2.创建 Statement
     * 3.为 Statement 设置 IN 参数
     */
    private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
        Statement stmt;
        // 获取数据库连接
        Connection connection = getConnection(statementLog);
        // 创建Statement对象
        stmt = handler.prepare(connection, transaction.getTimeout());
        // 处理占位符
        // 为 Statement 设置 IN 参数
        handler.parameterize(stmt);
        return stmt;
    }

}
